﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Collections;

namespace DotNET4Study
{
    class ThreadWithParametersStudy
    {
        private Thread[] threads;
        private int thrs = 10;//线程数量  
        private ArrayList stringList;
        private event EventHandler OnNumberClear;//数据删除完引发的事件  
        public ThreadWithParametersStudy(int number)
        {
            stringList = new ArrayList();
            for (int i = 0; i < number; i++)
            {
                stringList.Add(i.ToString());
            }
            threads = new Thread[thrs];
            for (int i = 0; i < thrs; i++)
            {
                threads[i] = new Thread(new ParameterizedThreadStart(run));
                threads[i].Name = "线程:" + (i + 1);
            }
            OnNumberClear += new EventHandler(ThreadDemo_OnNumberClear);
        }
        //public void Action()
        //{
        //    for (int i = 0; i < thrs; i++)
        //    {
        //        threads[i].Start((object)"Prince");
        //    }
        //}
        //注意参数一定要是 object 类型。多参数的话可以考虑用 struct类型  
        public void run(object para)
        {
            string stringValue = null;
            while (true)
            {
                Monitor.Enter(this);
                stringValue = (string)stringList[0];
                Console.WriteLine(Thread.CurrentThread.Name + "删除了:" + para + " === " + stringValue);
                stringList.RemoveAt(0);
                if (stringList.Count == 0)
                {
                    OnNumberClear(null, null);
                }
                Monitor.Exit(this);
                Thread.Sleep(2000);
            }
        }
        void ThreadDemo_OnNumberClear(object sender, EventArgs e)
        {
            Console.WriteLine("执行完所有的线程");
            for (int i = 0; i < thrs; i++)
                threads[i].Abort();
        }
    }
}
